package com.yifeng.repo.micro.service.server.engine.log.sqllog;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zyh
 */
@Slf4j
public class SqlLogInterceptor implements InnerInterceptor {
    private static final Set<String> SQL_SET = new HashSet<>(128);
    private static Boolean SQL_PRINT_ENABLE = false;

    @Override
    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
        if(!SQL_PRINT_ENABLE) {
            return;
        }
        try {
            SQL_SET.add(sh.getBoundSql().getSql().replaceAll("\n", ""));
        } catch (Exception e) {
            log.error("save sql failed, error={}", e.getMessage());
        }
    }

    public static void enable() {
        SQL_PRINT_ENABLE = true;
    }

    public static void disable() {
        SQL_PRINT_ENABLE = false;
    }

    public static Boolean isEnabled() {
        return SQL_PRINT_ENABLE;
    }
    public static List<String> getSqlList() {
        return new ArrayList<>(SQL_SET);
    }

    public static void clear() {
        SQL_SET.clear();
        log.info("sql set clear success");
    }
}
